//
//  YSCountDown.m
//  YSCountDownDemo
//
//  Created by FDC-iOS on 2017/4/21.
//  Copyright © 2017年 meilun. All rights reserved.
//



#import "YSCountDown.h"
#import "GBNetWorking.h"
@interface YSCountDown()
{
    dispatch_source_t _timer;
    NSDateFormatter *dateFormatter;
    
    
}
@property (nonatomic, copy)  updateTimer updateTimer;

@end

@implementation YSCountDown

- (instancetype)init{
    self = [super init];
    if (self) {
    [self destoryTimer];
    }
    return self;
}


- (void)updateEndtimer:(updateTimer)updateTimer
{
    _updateTimer = updateTimer;
    
    WSELF(weakSelf);
    if (_timer==nil) {
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
        dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
        dispatch_source_set_event_handler(_timer, ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                
          
                NSDate * sjDate = [NSDate date];   //手机时间
                NSTimeInterval sjInteger = [sjDate timeIntervalSince1970];  // 手机当前时间戳

                if (weakSelf.updateTimer) {
                    weakSelf.updateTimer(sjInteger);
                }
                
                
                //            }
                /*
                 for (UITableViewCell * cell in cells) {
                 NSDate * sjDate = [NSDate date];   //手机时间
                 NSInteger sjInteger = [sjDate timeIntervalSince1970];  // 手机当前时间戳
                 NSString* tempEndTime;
                 if ([dataList[0] isKindOfClass:[NSArray class]]) {
                 NSInteger section = cell.tag / 1000;
                 NSInteger row = cell.tag % 1000;
                 tempEndTime = dataList[section][row];
                 }else {
                 tempEndTime = dataList[cell.tag];
                 }
                 for (UIView * labText in cell.contentView.subviews) {
                 if (labText.tag == 1314) {
                 UILabel * textLabel = (UILabel *)labText;
                 NSInteger endTime = tempEndTime.longLongValue + _less;
                 
                 textLabel.text = [self getNowTimeWithString:endTime :sjInteger];
                 
                 
                 //                            if ([textLabel.text isEqualToString:@"活动已经结束！"]) {
                 //                                textLabel.textColor = [UIColor redColor];
                 //                            }else{
                 //                                textLabel.textColor = [UIColor orangeColor];
                 //                            }
                 }
                 }
                 */
                
                //                }
            });
        });
        dispatch_resume(_timer); // 启动定时器
    }
    
    
}

/// 滑动过快的时候不会闪
- (NSString *)countDownString:(NSTimeInterval )aTimeString :(timerType)type{
    NSDate * sjDate = [NSDate date];   //手机时间
    NSInteger sjInteger = [sjDate timeIntervalSince1970];  // 手机当前时间戳

    return [self getNowTimeWithString:aTimeString :sjInteger :type];
}

// 传入结束时间 | 计算与当前时间的差值
-(NSString *)getNowTimeWithString:(NSTimeInterval )aTimeString :(NSTimeInterval)startTime :(timerType)type{

    NSTimeInterval timeInterval = (aTimeString +self.less)- startTime;
    //    NSLog(@"%f",timeInterval);1511359020
    
    int days = (int)(timeInterval/(3600*24));
    int hours = (int)((timeInterval-days*24*3600)/3600);
    int minutes = (int)(timeInterval-days*24*3600-hours*3600)/60;
    int seconds = timeInterval-days*24*3600-hours*3600-minutes*60;
    
//    int seconds = (int)timeInterval %60;//秒
//    int minutes = (int)timeInterval /60%60;
//    int hours = (int)timeInterval / (24 *3600)%3600;
//    int days = (int)timeInterval / (24 *3600);
    
    
    NSString *dayStr;NSString *hoursStr;NSString *minutesStr;NSString *secondsStr;
    //天
    dayStr = [NSString stringWithFormat:@"%d",days];
    //小时
    hoursStr = [NSString stringWithFormat:@"%d",hours];
    //分钟
    if(minutes<10)
        minutesStr = [NSString stringWithFormat:@"0%d",minutes];
    else
        minutesStr = [NSString stringWithFormat:@"%d",minutes];
    //秒
    if(seconds < 10)
        secondsStr = [NSString stringWithFormat:@"0%d", seconds];
    else
        secondsStr = [NSString stringWithFormat:@"%d",seconds];
    
    
    if (_isPlusTime) {
        ///////////////////新增
        if (hours>=0&&minutes>=0&&seconds>=0) {
            return @"活动未开始！";
        }
        hours = -hours;
        minutes = -minutes;
        seconds = - seconds;
        ///////////////////新增
    }else {
        if (hours<=0&&minutes<=0&&seconds<=0) {
            return @"已经结束！";
        }
    }
    
    

    if (type==timerTypeDay) {
        if (days>0) {
            return [NSString stringWithFormat:@"%@天%@小时%@分%@秒", dayStr,hoursStr, minutesStr,secondsStr];
            //        return [NSString stringWithFormat:@"%zd天 %zd小时 %zd分 %zd秒", days,hours,minutes,seconds];
            //        return [NSString stringWithFormat:@"%zd:%zd:%zd",hours,minutes,seconds];
        }
        else
        {
          
          return [NSString stringWithFormat:@"%@小时%@分%@秒", hoursStr, minutesStr,secondsStr];
        }
        
        
    }else
    {
        if (type==timerTypeHours) {
            return [NSString stringWithFormat:@"%@小时%@分%@秒",hoursStr, minutesStr,secondsStr];
        }else if (type==timerTypeMinutes)
        {
         return [NSString stringWithFormat:@"%@分%@秒",minutesStr,secondsStr];
        }else
        {
         return [NSString stringWithFormat:@"%@秒",secondsStr];
        }
    }
    
    //    return [NSString stringWithFormat:@"%@小时 %@分 %@秒",hoursStr , minutesStr,secondsStr];
    //    return [NSString stringWithFormat:@"%zd小时 %zd分 %zd秒",hours , minutes,seconds];
//    return [NSString stringWithFormat:@"%zd:%zd:%zd",hours,minutes,seconds];
    /*
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *timeDate = [dateFormatter dateFromString:model.created_at];//model.created_at 时间
    //八小时时区
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:timeDate];
    NSDate *mydate = [timeDate dateByAddingTimeInterval:interval];
    NSDate *nowDate = [[NSDate date]dateByAddingTimeInterval:interval];
    //两个时间间隔
    NSTimeInterval timeInterval = [mydate timeIntervalSinceDate:nowDate];
    timeInterval = -timeInterval;
    long temp = 0;
    //    NSString *time;
    if (timeInterval<60) {
        self.timeLabel.text = [NSString stringWithFormat:@"刚刚"];
    }else if ((temp = timeInterval/60)<60){
        self.timeLabel.text = [NSString stringWithFormat:@"%ld分钟前",temp];
    }else if ((temp = timeInterval/(60*60))<24){
        self.timeLabel.text = [NSString stringWithFormat:@"%ld小时前",temp];
    }else if((temp = timeInterval/(24*60*60))<30){
        self.timeLabel.text = [NSString stringWithFormat:@"%ld天前",temp];
    }else if (((temp = timeInterval/(24*60*60*30)))<12){
        self.timeLabel.text = [NSString stringWithFormat:@"%ld月前",temp];
    }else {
        temp = timeInterval/(24*60*60*30*12);
        self.timeLabel.text = [NSString stringWithFormat:@"%ld年前",temp];
    }
     */
    
    
}



/// 回传时间的变化
-(void)countDownWithPER_SECBlock:(void (^)())PER_SECBlock{
    if (_timer==nil) {
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
        dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
        dispatch_source_set_event_handler(_timer, ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                PER_SECBlock(); // 回传时间的变化
            });
        });
        dispatch_resume(_timer); // 启动定时器
    }
}

/**
 *  主动销毁定时器
 */
-(void)destoryTimer{
    if (_timer) {
        dispatch_source_cancel(_timer);
        _timer = nil;
    }
}

-(void)dealloc{
    NSLog(@"%s dealloc",object_getClassName(self));
    
}

@end
